package cn.com.utt.unms.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.com.utt.common.exception.BusinessException;
import cn.com.utt.common.util.GraphicsMagickUtil;
import cn.com.utt.common.util.WxApi;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.TableInput;
import cn.com.utt.common.vo.TableOutput;
import cn.com.utt.unms.mapper.PageListMapper;
import cn.com.utt.unms.mapper.PagePubMapper;
import cn.com.utt.unms.mapper.WifiCfgMapper;
import cn.com.utt.unms.pojo.Page;
import cn.com.utt.unms.pojo.PagePub;
import cn.com.utt.unms.pojo.WXAuthorizer;
import cn.com.utt.unms.pojo.WifiConf;
import cn.com.utt.unms.service.WifiCfgService;
import cn.com.utt.unms.vo.ShopInfo;
import cn.com.utt.unms.vo.ShopList;
import cn.com.utt.unms.vo.WifiConfInfo;

@Service("wifiCfgService")
public class WifiCfgServiceImpl implements WifiCfgService {

	@Autowired
	private WifiCfgMapper wifiCfgMapper;
	
	@Autowired
	private PageListMapper pageListMapper;
	
	@Autowired
	private PagePubMapper pagePubMapper;

	private static String needattentionpage = "auth.greenwifi.com.cn/wxattention.html";

	private static String finishpage = "auth.greenwifi.com.cn/finish.html";

	private static String upload = "/data/www/upload/";

	private static String logo = "/data/www/logo/";
	
	private static String qrcodeMark = "/data/www/images/wx_mark.png";

	@Override
	public ShopList queryWXShopList(long cfgId) throws BusinessException {
		ShopList shopList = new ShopList();
		List<ShopInfo> shops = new ArrayList<ShopInfo>();
		WXAuthorizer wxAuthorizer = wifiCfgMapper.queryWxAuthorizer(cfgId);
		if (wxAuthorizer != null) {
			String authAppId = wxAuthorizer.getAppId();
			// 获取authorizer_access_token
			JSONObject resp = WxApi.authorizerAccessToken(cfgId, authAppId);
			if (resp.getInteger("errcode") != null && resp.getInteger("errcode") > 0) {
				// 获取token出错
				throw new BusinessException("refresh token error");
			}
			String accessToken = resp.getString("authorizer_access_token");

			if (accessToken != null && accessToken.length() > 0) {
				// 获取门店信息
				resp = WxApi.getShopList(accessToken, 1, 20);
				if (resp.getInteger("errcode") != null && resp.getInteger("errcode") > 0) {
					// 获取token出错
					throw new BusinessException("get shop list error");
				}
				// 组装门店信息
				if (resp.getString("data") != null) {
					ShopList list = JSON.parseObject(resp.getString("data"), ShopList.class);
					int count = list.getPagecount();
					int index = list.getPageindex();
					shopList.setPagecount(count);
					shopList.setPageindex(index);
					for (ShopInfo shopInfo : list.getRecords()) {
						if (shopInfo.getProtocolType() == 31) {
							shops.add(shopInfo);
						}
					}
					for (int i = index + 1; i <= count; i++) {
						resp = WxApi.getShopList(accessToken, i, 20);
						if (resp.getInteger("errcode") != null && resp.getInteger("errcode") > 0) {
							// 获取token出错
							throw new BusinessException("get shop list error");
						}
						// 组装门店信息
						if (resp.getString("data") != null) {
							list = JSON.parseObject(resp.getString("data"), ShopList.class);
							for (ShopInfo shopInfo : list.getRecords()) {
								if (shopInfo.getProtocolType() == 31) {
									shops.add(shopInfo);
								}
							}
						}
					}
				}

			}

		}
		shopList.setRecords(shops);
		shopList.setTotalcount(shops.size());
		return shopList;
	}

	@Override
	public WifiConf queryWifiConfById(long id) {
		return wifiCfgMapper.queryWifiConfById(id);
	}

	@Override
	public WXAuthorizer queryWxAuthorizer(long cfgId) {
		return wifiCfgMapper.queryWxAuthorizer(cfgId);
	}

	private int setFinishPage(long cfgId, long storeId, String url) throws BusinessException {
		WXAuthorizer wxAuthorizer = wifiCfgMapper.queryWxAuthorizer(cfgId);
		if (wxAuthorizer != null) {
			String authAppId = wxAuthorizer.getAppId();
			// 获取authorizer_access_token
			JSONObject result = WxApi.authorizerAccessToken(cfgId, authAppId);
			if (result.getInteger("errcode") != null && result.getInteger("errcode") > 0) {
				// 获取token出错
				throw new BusinessException("refresh token error");
			}
			String accessToken = result.getString("authorizer_access_token");
			if (accessToken != null && accessToken.length() > 0) {
				// 获取门店信息
				JSONObject resp = WxApi.setFinishPage(accessToken, url, storeId);
				if (resp.getInteger("errcode") != null && resp.getInteger("errcode") == 0) {
					// 设置成功
					return 1;
				} else {
					return 0;
				}
			}
		}

		return 0;
	}

	private String getWiFiSecret(long cfgId, long storeId, String ssid) throws BusinessException {
		WXAuthorizer wxAuthorizer = wifiCfgMapper.queryWxAuthorizer(cfgId);
		if (wxAuthorizer != null) {
			String authAppId = wxAuthorizer.getAppId();
			// 获取authorizer_access_token
			JSONObject resp = WxApi.authorizerAccessToken(cfgId, authAppId);
			if (resp.getInteger("errcode") != null && resp.getInteger("errcode") > 0) {
				// 获取token出错
				throw new BusinessException("refresh token error");
			}
			String accessToken = resp.getString("authorizer_access_token");
			if (accessToken != null && accessToken.length() > 0) {
				// 获取门店信息
				resp = WxApi.getShopSecret(accessToken, ssid, storeId);
				if (resp.getInteger("errcode") != null && resp.getInteger("errcode") > 0) {
					// 获取token出错
					throw new BusinessException("register error");
				}

				if (resp.getJSONObject("data") != null) {
					return resp.getJSONObject("data").getString("secretkey");
				}
			}

		}
		return null;
	}

	public void copyFile(File source, File target) throws BusinessException, IOException {
		try {
			FileInputStream fstream = null;
			FileOutputStream out = null;
			try {
				fstream = new FileInputStream(source);
				out = new FileOutputStream(target.toString());
				byte[] b = new byte[1024 * 5];
				int len;
				while ((len = fstream.read(b)) != -1) {
					out.write(b, 0, len);
				}
			} catch (Exception e) {
				throw new BusinessException("copyFile 发生异常", e);
			} finally {
				if (fstream != null) {
					fstream.close();
				}
				if (out != null) {
					out.close();
				}
			}
		} catch (Exception e) {
			throw new BusinessException("copyFile 发生异常", e);
		}
	}
	
	/**
	 * 删除单个文件
	 * 
	 * @param sPath
	 *            被删除文件的文件名
	 * @return 单个文件删除成功返回true，否则返回false
	 */
	private boolean deleteFile(String sPath) {
		boolean flag = false;
		File file = new File(sPath);
		// 路径为文件且不为空则进行删除
		if (file.isFile() && file.exists()) {
			file.delete();
			flag = true;
		}
		return flag;
	}

	@Override
	public void updateWifiConf(WifiConf conf, long cfgId) throws BusinessException {
		try {

			WifiConf wc = wifiCfgMapper.queryWifiConfById(cfgId);
			String source = "";
			String target = "";
			wc.setAccessLimit(conf.getAccessLimit());
			wc.setConcurrentLimit(conf.getConcurrentLimit());
			wc.setAccessType(conf.getAccessType());
			byte wxAuthType = 0;
			if (conf.getWxAuthType() != null && !conf.getWxAuthType().equals("")) {
				wxAuthType = conf.getWxAuthType();
			} else {
				wxAuthType = 0;
			}
			wc.setName(conf.getName());
			wc.setWxAuthType(wxAuthType);
			wc.setFreeRxLimit(conf.getFreeRxLimit());
			wc.setFreeTmLimit(conf.getFreeTmLimit());
			wc.setPhoneRxLimit(conf.getPhoneRxLimit());
			wc.setPhoneTmLimit(conf.getPhoneTmLimit());
			wc.setSimEnable(conf.getSimEnable());
			wc.setWxAccount(conf.getWxAccount());
			wc.setWxPcFree(conf.getWxPcFree());
			wc.setWxRxLimit(conf.getWxRxLimit());
			wc.setWxTmLimit(conf.getWxTmLimit());
			wc.setWxSid(conf.getWxSid());
			wc.setWxToken(conf.getWxToken());
			if (conf.getWxSsid() != null && conf.getWxSsid().length() > 0 && conf.getMpAppId() != null
					&& conf.getMpAppId().length() > 0) {
				wc.setWxSsid(conf.getWxSsid());
				wc.setMpAppId(conf.getMpAppId());
			}
			wc.setWxStoreId(conf.getWxStoreId());
			wc.setMpAppSecret(conf.getMpAppSecret());
			if (((conf.getAccessType() & 4) == 4) && wxAuthType == 2) {
				long storeId = Long.parseLong(conf.getWxStoreId());
				// 通过微信接口获取secret
				if ((conf.getWxStoreId() != null && !conf.getWxStoreId().equals(wc.getWxStoreId()))
						|| (conf.getWxSsid() != null && !conf.getWxSsid().equals(wc.getWxSsid()))
						|| (wc.getMpAppSecret() == null || wc.getMpAppSecret().length() == 0)) {
					// 门店或ssid变化，需要重新获取secret
					String secret = getWiFiSecret(cfgId, storeId, conf.getWxSsid());
					System.out.println(secret);
					wc.setMpAppSecret(secret);
				}
				// 设置认证完成页面
				if (conf.getNeedAttention() == 1) {
					setFinishPage(cfgId, storeId, needattentionpage);
				} else {
					if (wc.getNeedAttention() == 1) {
						// 取消了强制关注
						setFinishPage(cfgId, storeId, finishpage);
					}
				}
			}
			wc.setNeedAttention(conf.getNeedAttention());
			wc.setAccountRxLimit(conf.getAccountRxLimit());
			wc.setAccountTmLimit(conf.getAccountTmLimit());

			if (conf.getSemacodePath() != null && !conf.getSemacodePath().equals("")) {
				source = upload + conf.getSemacodePath();
				target = logo + conf.getSemacodePath();
				if (!conf.getSemacodePath().equals(wc.getSemacodePath())) {
					copyFile(new File(source), new File(target));
					deleteFile(upload + conf.getSemacodePath());
					if (wc.getSemacodePath() != null && !wc.getSemacodePath().equals("")) {
						deleteFile(logo + wc.getSemacodePath());// 删除原先微信图片
					}
					wc.setSemacodePath(conf.getSemacodePath());
					wc.setWxSacnCode("qr" + conf.getSemacodePath());
					String targetImgPath = logo + wc.getWxSacnCode();
					
					System.out.println("target:" + target);
					int width = GraphicsMagickUtil.getWidth(target);
					int height = GraphicsMagickUtil.getHeight(target);
					if (width != 258 || height != 258) {
						String savePath = logo + "tmp" + conf.getSemacodePath();
						GraphicsMagickUtil.zoomImage(258, 258, target, savePath);
						GraphicsMagickUtil.composite(qrcodeMark, savePath, targetImgPath);
					} else {
						GraphicsMagickUtil.composite(qrcodeMark, target, targetImgPath);
					}
				}
			}
			
			//判断是否选择了认证页面
			if(conf.getPlId() != null && conf.getPlId() > 0 && !conf.getPlId().equals(wc.getPlId())){
				// 通过page_list_id 查询 pages
				List<Page> pages = pageListMapper.queryPages(conf.getPlId());
				if(pages != null){
					for (Page page : pages) {
						byte typeB = (byte) (page.getTmId() - 10000000);
						PagePub pagePub = new PagePub();
						pagePub.setPageId(page.getId());
						pagePub.setCfgId(cfgId);
						pagePub.setPath(page.getPath());
						pagePub.setPageType(typeB);
						pagePubMapper.deletePagePubByType(typeB, cfgId);
						pagePubMapper.savePagePub(pagePub);
					}
				}
				wc.setPlId(conf.getPlId());
				wc.setPageDir("user_defined");
			}
			wifiCfgMapper.update(wc);
			// TODO 存入缓存
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException(e.getMessage(), e);
		}
	}

	@Override
	public void saveWifiConf(WifiConf conf) {
		wifiCfgMapper.save(conf);
	}

	@Override
	public TableOutput<WifiConfInfo> queryByCondition(TableInput input, Long userId) {
		
		Map<String, Object> conditions = new HashMap<>();
		conditions.put("searchs", input.getSearch());
		conditions.put("userId", userId);
		if (input.getOrder() != null) {
			conditions.put("orderColumn", input.getOrder().getColumn());
			conditions.put("orderDirection", input.getOrder().getDir());
		}
		conditions.put("start", input.getStart());
		conditions.put("rows", input.getRows());
		int total = wifiCfgMapper.countByCondition(conditions);
		List<WifiConf> confs = wifiCfgMapper.queryByCondition(conditions);
		List<WifiConfInfo> infos = new ArrayList<>();
		for (WifiConf wifiConf : confs) {
			WifiConfInfo info = new WifiConfInfo();
			info.setId(wifiConf.getId());
			info.setName(wifiConf.getName());
			if (wifiConf.getPlId() != null){
				info.setPage(pageListMapper.queryById(wifiConf.getPlId().longValue()).getName());
			}
			infos.add(info);
		}
		TableOutput<WifiConfInfo> output = new TableOutput<>();
		
		output.setList(infos);
		output.setTotal(total);
		output.setRows(input.getRows());
		output.setStart(input.getStart());
		return output;
	}

	@Override
	public List<WifiConf> queryAll(long userId) {
		return wifiCfgMapper.queryAll(userId);
	}

	@Override
	@Transactional
	public RestResult delete(List<Long> cfgIds, Long userId) {
		RestResult result = new RestResult();
		if (cfgIds != null && cfgIds.size() > 0) {
			
			wifiCfgMapper.delete(cfgIds);
		} else {
			result.setErrorCode(1);
			result.setErrorMsg("参数错误");
			return result;
		}
		result.setErrorMsg("删除成功");
		return result;
	}

}